<template>
  <view id="appointmentDetail" class="page">
    <view class="state"> {{ state }} </view>
    <view class="divider"></view>
    <view class="store" @tap="onTapStore">
      <view class="title">
        <view class="name">{{
          detail && detail.community && detail.community.name
        }}</view>
        <view class="distance">距您{{ distance }}km</view>
      </view>
      <view class="address">
        <image class="icon-left" src="../../../image/icon_location.png" />
        <view class="text">
          {{ detail && detail.community && detail.community.address }}
        </view>
        <image
          class="map"
          src="../../../image/icon_map.png"
          @tap="onMap($event)"
        />
        <image
          class="phone"
          src="../../../image/icon_phone2.png"
          @tap="onCall($event)"
        />
      </view>
    </view>

    <view class="box-service">
      <view>
        <image
          class="icon-appointment"
          src="../../../image/icon_appointment.png"
        />
        <text class="service-name">预约服务</text>
      </view>
      <view class="item-service" v-if="detail && detail.service">
        <image class="img" :src="imgUrl + detail.service.url" />
        <view class="name">{{
          detail && detail.service && detail.service.name
        }}</view>
      </view>
      <view class="item-info">
        <text class="left-title">预约时间</text>
        <text class="right-value"> {{ appointmentTime }}</text>
      </view>
      <view class="item-info">
        <text class="left-title">预约人手机号</text>
        <text class="right-value">{{ detail && detail.mobile }}</text>
      </view>
      <view class="item-info">
        <text class="left-title">预约人车辆</text>
        <text class="right-value">{{ detail && detail.plateNo }}</text>
      </view>
    </view>

    <view class="box-order">
      <view>
        <image class="icon-appointment" src="../../../image/icon_order.png" />
        <text class="service-name">预约订单</text>
      </view>
      <view class="item-info">
        <text class="left-title">预约单号</text>
        <text class="right-value">{{ detail && detail.orderNumber }}</text>
      </view>
      <view class="item-info">
        <text class="left-title">创建时间</text>
        <text class="right-value">{{ detail && detail.createTime }}</text>
      </view>
      <view class="item-info">
        <text class="left-title">预约备注</text>
        <text class="right-value">{{
          detail && detail.remark ? detail.remark : "--"
        }}</text>
      </view>
    </view>
    <view class="box-evaluate" v-if="detail && detail.status == 2 && evaluates">
      <view>
        <image
          class="icon-appointment"
          src="../../../image/icon_evaluate.png"
        />
        <text class="service-name">我的评价</text>
      </view>
      <view class="evaluate-base-info">
        <image
          class="avatar"
          v-if="detail && detail.headImgUrl"
          :src="detail.headImgUrl"
        />
        <image v-else class="avatar" src="../../../image/img_header.png" />
        <view class="user-info">
          <text class="name" v-if="detail.isAnonymous">匿名用户</text>
          <text class="name" v-else-if="detail">{{
            detail.nickName || "匿名用户"
          }}</text>
          <view class="evaluate-time">
            {{ evaluates && evaluates.createTime }}
          </view>

          <view class="row-score" v-if="score">
            <rate-star
              :percent="score * 20"
              width="10"
              height="12"
              id="detailRateStarTotal"
              disabled
            />
            <view class="text"> {{ score }}<text class="text2">分</text></view>
          </view>
        </view>
      </view>
      <view class="evaluate-content">
        {{ evaluates && evaluates.content }}
      </view>
      <view class="evaluate-img">
        <image
          class="evaluate-img-item"
          :src="imgUrl + image"
          v-for="image in evaluatesImgs"
          :key="image"
          mode="aspectFill"
          @tap="onTapPreviewImg(image, evaluatesImgs)"
        />
      </view>
      <view class="shop-reply" v-if="replyContent">
        <image class="bg" src="../../../image/shop_reply_bg.png"></image>
        <text class="reply-title">门店回复：</text>
        <text class="reply-content">
          {{ replyContent.content }}
        </text>
      </view>
    </view>
    <view
      class="btn-evaluate"
      v-if="detail.status == 0 || detail.status == 1"
      @tap="onEvaluate"
    >
      <text>{{ btnTxt }}</text></view
    >
  </view>
</template>
<script>
import Taro from "@tarojs/taro";
import "./appointmentDetail.less";
import { getMapDistance } from "../../../check.js";
import rateStar from "../../../components/rate-star/rate-star.vue";
import { request } from "../../../util/axios.js";
import bulterApi from "@souche2014/bulter-api";
const api = bulterApi({ partner: "IOParking" });
const API_CarCode = process.env.IOParking.API_CARCODE;
var common = require("../../../common.js");
export default {
  name: "appointmentDetail",
  data() {
    return {
      imgUrl: process.env.IOParking.IMAGE_BASE,
      apiBaseUrl: process.env.IOParking.API_HOST, //请求头部
      detail: {},
      evaluates: {},
      evaluatesImgs: [],
      anonymousDesc: "",
      score: "5",
      state: "",
      appointmentTime: "",
      replyContent: null,
      btnTxt: "立即评价",
      id: "",
      distance: 0, //当前位置距离门店km
    };
  },
  //mixins:[authorize],
  components: { rateStar },
  mounted() {},

  onLoad: function (options) {
    console.log("参数:", JSON.stringify(options));
    this.id = options.id;
    try {
      var openId = Taro.getStorageSync("openId");
      if (!openId) {
        this.wx_login();
      } else {
        this.getDetailInfo();
      }
    } catch (error) {
      this.wx_login();
    }
  },
  created() {},
  onPullDownRefresh() {
    this.getDetailInfo();
    Taro.stopPullDownRefresh(); //结束刷新
  },
  methods: {
    wx_login() {
      api
        .getUserInfo({
          scope: "all",
        })
        .then((resp) => {
          if (resp.success) {
            if (resp.data == "mock") {
              return;
            }
            this.getUserInfos(resp.data);
          } else {
            console.log("err is ", resp.message, "err code is ", resp.code);
          }
        });
    },
    getUserInfos(authCode) {
      Taro.request({
        url: this.apiBaseUrl + "/weixin/souchegetuser?authCode=" + authCode,
        data: {},
        header: {
          "content-type": "application/json", // 默认值
        },
        method: "GET",
        success: (res) => {
          if (res.data.isSuccess) {
            var userOpenId = res.data.data.openId;
            let mobileRes = res.data.data.phoneNum;
            if (userOpenId) {
              Taro.setStorage({
                key: "openId",
                data: userOpenId,
              });
            }
            if (mobileRes) {
              Taro.setStorage({
                key: "mobile",
                data: mobileRes,
              });
            }
            //获取预约详情
            this.getDetailInfo();
          }
        },
      });
    },

    getDetailInfo() {
      if (!this.id) {
        return;
      }
      let url = API_CarCode + "/reservationorder/getinfo";
      Taro.request({
        url: url,
        data: {
          id: this.id,
          openid: Taro.getStorageSync("openId"),
        },
        header: {
          "content-type": "application/json", // 默认值
        },
        method: "GET",
        success: (res) => {
          if (res.data.isSuccess) {
            this.detail = res.data.data;
            this.setState();
            this.appointmentTime = this.setAppointmentTime();
            this.setEvaluateData();

            //获取定位，计算距离
            this.getLocation();
          } else {
            Taro.showToast({
              title: res.data.message,
              icon: "error",
              duration: 1000,
              mask: true,
            });
          }
        },
      });
    },
    setState() {
      if (this.detail) {
        if (this.detail.status == 0) {
          this.state = "未到店";
          this.btnTxt = "取消预约";
        } else if (this.detail.status == 1) {
          this.state = "已完成";
          this.btnTxt = "立即评价";
        } else if (this.detail.status == 2) {
          this.state = "已评价";
        } else if (this.detail.status == 3) {
          this.state = "已过期";
        } else if (this.detail.status == 4) {
          this.state = "已取消";
        }
      }
    },
    setAppointmentTime() {
      if (!this.detail) {
        return "";
      }

      let date =
        this.detail.reservationDate && this.detail.reservationDate.split(" ");
      let time = `${date && date[0]} ${
        this.detail.timeSlot && this.detail.timeSlot.startTime
      }-${this.detail.timeSlot && this.detail.timeSlot.endTime}`;
      return time;
    },
    setEvaluateData() {
      if (
        !this.detail ||
        !this.detail.evaluates ||
        this.detail.evaluates.length < 1
      ) {
        this.evaluates = null;
        return;
      }
      this.evaluates = this.detail.evaluates[0];
      if (this.evaluates.imageUrls) {
        this.evaluatesImgs = this.evaluates.imageUrls.split(",");
      }
      // 匿名评价/公开评价
      if (this.evaluates.isAnonymous) {
        this.anonymousDesc = "匿名评价";
      } else {
        this.anonymousDesc = "公开评价";
      }
      this.score = this.evaluates.score;

      //回复相关信息
      let children = this.evaluates.children;
      if (children && children.length > 0) {
        this.replyContent = children[0];
      }
    },
    cancelOrder() {
      Taro.showLoading({
        title: "加载中",
        mask: true,
      });
      Taro.request({
        url:
          API_CarCode +
          "reservationorder/cancel?id=" +
          this.id +
          "&openId=" +
          Taro.getStorageSync("openId"),
        data: {},
        header: {
          "content-type": "application/json", // 默认值
        },
        method: "GET",
        success: (res) => {
          Taro.hideLoading();
          if (res.data.isSuccess) {
            Taro.showToast({
              title: "取消成功",
              icon: "success",
              duration: 1000,
              mask: true,
            });
            this.getDetailInfo();
          } else {
            Taro.showToast({
              title: res.data.message,
              icon: "error",
              duration: 1000,
              mask: true,
            });
          }
        },
      });
    },
    onTapStore() {
      if (!this.detail) {
        return;
      }
      Taro.redirectTo({
        url: `../storeDetail/storeDetail?communityId=${this.detail.communityId}`,
      });
    },
    onEvaluate() {
      if (!this.detail) {
        return;
      }
      if (this.detail.status == 0) {
        //取消预约
        Taro.showModal({
          content: "确定取消本次预约吗？",
          confirmText: "确定取消",
          cancelText: "点错了",
          success: (res) => {
            if (res.confirm) {
              this.cancelOrder();
            } else if (res.cancel) {
              //取消
            }
          },
        });
      } else if (this.detail.status == 1) {
        //立即评价
        Taro.navigateTo({
          url: `../evaluate/evaluate?id=${this.id}`,
        });
      }
    },
    getLocation() {
      if (this.distance > 0) {
        //减少重复定位损耗
        return;
      }
      Taro.getLocation({
        type: "gcj02", //返回可以用于 Taro.openLocation的经纬度
        isHighAccuracy: true, //高精度定位
        highAccuracyExpireTime: 4000, //高精度定位超时时间(ms)，指定时间内返回最高精度，该值3000ms以上高精度定位才有效果
        success: (res) => {
          this.latitude = res.latitude;
          this.longitude = res.longitude;
          console.log("定位:", this.latitude, this.longitude);
          if (
            this.detail &&
            this.detail.community &&
            this.detail.community.longitude &&
            this.detail.community.latitude
          ) {
            this.distance = getMapDistance(
              this.latitude,
              this.longitude,
              this.detail.community.latitude,
              this.detail.community.longitude
            ).toFixed(1);
          }
        },
      });
    },
    onMap(e) {
      if (!this.detail) {
        return;
      }
      if (this.detail.community.longitude && this.detail.community.latitude) {
        let longitude = this.detail.community.longitude;
        let latitude = this.detail.community.latitude;
        Taro.openLocation({
          latitude,
          longitude,
          scale: 15,
        });
      } else {
        Taro.showToast({
          title: "未获取到门店坐标",
          icon: "none",
          duration: 1000,
          mask: true,
        });
      }
      e.stopPropagation();
    },
    onCall(e) {
      if (
        !this.detail ||
        !this.detail.community ||
        !this.detail.community.mobile
      ) {
        Taro.showToast({
          title: "未获取到门店电话",
          icon: "none",
          duration: 1000,
          mask: true,
        });
      } else {
        Taro.makePhoneCall({
          phoneNumber: this.detail.community.mobile,
        });
      }
      e.stopPropagation();
    },
    onTapPreviewImg(currentImg, list) {
      let imgUrls = list.map((item) => {
        item = this.imgUrl + item;
        return item;
      });
      Taro.previewImage({
        current: this.imgUrl + currentImg, // 当前显示图片的http链接
        urls: imgUrls, // 需要预览的图片http链接列表
      });
    },
    //end
  },
};
</script>
<style lang="less" scoped>
</style>

